package com.example.server.controller;

import com.example.server.handle.SessionCache;
import com.example.server.handle.TokenCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class MyController {

    /**
     * 客户端先登陆，才能进行连接
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/login")
    public Object login(@RequestParam String username, @RequestParam String password) {
        String token = UUID.randomUUID().toString().replace("-", "");
        log.info("客户端登陆成功，username:{}, token:{}", username, token);
        TokenCache.add(token, username);
        return token;
    }

    /**
     * 客户端退出
     * @param token
     * @return
     */
    @RequestMapping(value = "/logout")
    public Object logout(@RequestParam String token) {
        TokenCache.remove(token);
        return "ok";
    }

    /**
     * 给客户端发消息
     * @param sessionId
     * @param msg
     * @return
     */
    @RequestMapping(value = "/send")
    public Object send(@RequestParam(required = false) String sessionId, @RequestParam String msg) {
        SessionCache.sendMessage(sessionId, msg);
        return "ok";
    }

    /**
     * 主动关闭客户端连接
     * @param sessionId
     * @return
     */
    @RequestMapping(value = "/close")
    public Object close(@RequestParam String sessionId) {
        WebSocketSession session = SessionCache.get(sessionId);
        if (null != session) {
            try {
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                SessionCache.remove(sessionId);
            }
        }
        return "ok";
    }

    /**
     * 获取所有连接中的客户端列表
     * @return
     */
    @RequestMapping(value = "/getSessionList")
    public Object getSessionList() {
        return SessionCache.getAll();
    }
}
